/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package wisimconsole;

import java.awt.Color;
import java.awt.Component;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.EditorKit;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
//import org.eclipse.swt.graphics.GC;
import wiBase.WiObject;
import wiBase.baseObject.Event;
import wiBase.baseObject.Node;
import wiBase.baseObject.Packet;
import wiModel.WiModelAdapter;

/**
 *
 * @author brother
 */
public class InfoNodeFrame extends javax.swing.JFrame {

    WiSimConsole console = null;
    ArrayList<WiObject> data = new ArrayList<>();

    /**
     * Creates new form InfoNodeFrame
     */
    public InfoNodeFrame(WiSimConsole console) {
	this.console = console;
	initComponents();

	doc = jtp_event.getDocument();
	setFont();
	cb_page.setVisible(false);
	
	jl_nodes.setCellRenderer(new NodeListRenderer());
	try {
	    loadListNode();
	} catch (NullPointerException ex) {
	}

	jl_nodes.addMouseListener(new MouseAdapter() {
	    @Override
	    public void mouseClicked(MouseEvent event) {
		JList list = (JList) event.getSource();

		// Get index of item clicked

		int index = list.locationToIndex(event.getPoint());
		Object object = list.getModel().getElementAt(index);
		if (object instanceof Node) {
		    refreshData((Node) object);
		}
		// Repaint cell
		list.repaint(list.getCellBounds(index, index));
	    }
	});
    }
    int ITEM_PAGE = 20;

    private void refreshData(Node node) {

	System.gc();


	lbl_id.setText("Id: " + node.id);
	lbl_energy.setText("" + node.energy);
	lbl_location.setText(node.position.getX() + " - " + node.position.getY());
	lbl_range.setText("" + node.range);
	lbl_width.setText(node.size.getWidth() + "");
	lbl_height.setText(node.size.getHeight() + "");
	try {
	    Thread.sleep(0);
	} catch (InterruptedException ex) {
	}
	lstDataEventOfNode = console.getEngine().getNodeInfo(node.id);
	if (lstDataEventOfNode != null) {
	    try {
		doc.remove(0, doc.getLength());
	    } catch (BadLocationException ex) {
		return;
	    }
	    int sumEvent = lstDataEventOfNode.size();
	    lbl_sum_event.setText(sumEvent + " Events");
	    int page = sumEvent / ITEM_PAGE;

	    cb_page.removeAllItems();
	    System.out.println(lstDataEventOfNode.size() + "items");
	    System.out.println(page + "index");
	    if (page == 0) {
		cb_page.setVisible(false);
	    } else {
		cb_page.setVisible(true);
		for (int i = 0; i < page; i++) {
		    cb_page.addItem("Page " + (i + 1) + " Start: " + ((Event) lstDataEventOfNode.get(i * ITEM_PAGE)).time+"s");
		}
	    }


	    int i = 0;
	    for (WiObject object : lstDataEventOfNode) {
		i++;
		if (i < ITEM_PAGE) {
		    insertTextFormat(object);
		}

	    }
	}

    }
    Document doc = null;
    EditorKit kit;
    ArrayList<WiObject> lstDataEventOfNode = new ArrayList<>();
    SimpleAttributeSet attDef = new SimpleAttributeSet();
    SimpleAttributeSet attType = new SimpleAttributeSet();
    SimpleAttributeSet attTime = new SimpleAttributeSet();
    SimpleAttributeSet attPacket = new SimpleAttributeSet();
    SimpleAttributeSet attNode = new SimpleAttributeSet();

    private void setFont() {
	int fontSizeDefault = 14;

	StyleConstants.setFontSize(attDef, fontSizeDefault);
	StyleConstants.setForeground(attDef, Color.black);

	StyleConstants.setFontSize(attType, fontSizeDefault);
	StyleConstants.setForeground(attType, Color.green);

	StyleConstants.setFontSize(attTime, fontSizeDefault);
	StyleConstants.setForeground(attTime, Color.blue);

	StyleConstants.setFontSize(attPacket, fontSizeDefault);
	StyleConstants.setForeground(attPacket, Color.black);

	StyleConstants.setFontSize(attNode, fontSizeDefault);
	StyleConstants.setForeground(attNode, Color.blue);
    }

    private void insertTextFormat(WiObject object) {
	if (object instanceof Event) {
	    try {
		doc.insertString(doc.getLength(), "Type:\t " + ((Event) object).type + "\n", attType);
		doc.insertString(doc.getLength(), "Time:\t " + ((Event) object).time + "\n", attTime);
		doc.insertString(doc.getLength(), "Packet Id:\t " + ((Event) object).packetId + "\n", attPacket);
		doc.insertString(doc.getLength(), "-----------Event Info----------" + "\n", attDef);
		doc.insertString(doc.getLength(), "Event: " + ((Event) object).toString() + "\n", attDef);

	    } catch (BadLocationException ex) {
	    }
	}
	
    }

    @Override
    public void setVisible(boolean b) {
	super.setVisible(b);
	if (b) {
	    loadListNode();
	}
    }

    private void loadListNode() throws NullPointerException {
	data = console.getEngine().getListNodes();
	Collections.sort(data, new Comparator(){

	    @Override
	    public int compare(Object o1, Object o2) {
		return ((Node)o1).id-((Node)o2).id;
	    }
	    
	});
	jl_nodes.setListData(data.toArray());
    }

    class NodeListRenderer extends JLabel implements ListCellRenderer {

	@Override
	public Component getListCellRendererComponent(
		JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
	    setEnabled(list.isEnabled());
	    setOpaque(isSelected);
	    setFont(list.getFont());
	    setBackground(list.getBackground());
	    setForeground(list.getForeground());
	    if (isSelected && cellHasFocus) {
		setBackground(Color.YELLOW);
		setForeground(Color.RED);
		if (value instanceof Node) {
		    //refreshData((Node) value);
		}
	    }

	    if (value instanceof Node) {
		Node node = (Node) value;
		setText("id: " + node.id);
	    } else {
		setText("unknow");
	    }

	    return this;
	}
    }

    // Do not Edit here!!!
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel13 = new javax.swing.JLabel();
        lbl_width = new javax.swing.JLabel();
        lbl_height = new javax.swing.JLabel();
        lbl_energy = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        lbl_location = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        lbl_range = new javax.swing.JLabel();
        lbl_color = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        lbl_id = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtp_event = new javax.swing.JTextPane();
        btn_ok = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        lbl_sum_event = new javax.swing.JLabel();
        cb_page = new javax.swing.JComboBox();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jl_nodes = new javax.swing.JList();

        setTitle("Node Information");
        setLocationByPlatform(true);
        setName("info_node_frame"); // NOI18N

        jLabel13.setText("Height:");

        lbl_width.setText("20px");

        lbl_height.setText("20px");

        lbl_energy.setText("200.00000");

        jLabel8.setText("Energy:");

        lbl_location.setText("5.00000 - 180.00000");

        jLabel6.setText("Location:");

        lbl_range.setText("0.000000005");

        lbl_color.setText("Red");

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel1.setText("Node:");

        jLabel11.setText("Width:");

        lbl_id.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lbl_id.setText("id=1");

        jLabel2.setText("Color:");

        jLabel4.setText("Range:");

        jtp_event.setBorder(javax.swing.BorderFactory.createTitledBorder("Event Relate to Node"));
        jtp_event.setText("Event id=0 type=send source-id=1");
        jtp_event.setOpaque(false);
        jScrollPane1.setViewportView(jtp_event);

        btn_ok.setText("OK");

        jLabel3.setText("Sum:");

        lbl_sum_event.setText("100");

        cb_page.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Page 1", "Page 2", "Page 3", "Page 4" }));
        cb_page.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cb_pageActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addComponent(jLabel4)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lbl_energy)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel13))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(lbl_location)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel11))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lbl_range)
                        .addGap(94, 94, 94)
                        .addComponent(jLabel2)))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbl_height)
                    .addComponent(lbl_color)
                    .addComponent(lbl_width))
                .addGap(0, 109, Short.MAX_VALUE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lbl_sum_event)
                        .addGap(18, 18, 18)
                        .addComponent(cb_page, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btn_ok, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lbl_id)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(lbl_id))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(lbl_range)
                    .addComponent(jLabel2)
                    .addComponent(lbl_color))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(lbl_location)
                    .addComponent(jLabel11)
                    .addComponent(lbl_width))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbl_energy)
                    .addComponent(jLabel8)
                    .addComponent(jLabel13)
                    .addComponent(lbl_height))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btn_ok)
                    .addComponent(jLabel3)
                    .addComponent(lbl_sum_event)
                    .addComponent(cb_page, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        jl_nodes.setBorder(javax.swing.BorderFactory.createTitledBorder("List Node"));
        jl_nodes.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane2.setViewportView(jl_nodes);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cb_pageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cb_pageActionPerformed
	JComboBox cb = (JComboBox) evt.getSource();
	String petName = (String) cb.getSelectedItem();
	int index = cb.getSelectedIndex();
	if (lstDataEventOfNode != null && index >= 0) {
	    try {
		doc.remove(0, doc.getLength());
	    } catch (BadLocationException ex) {
	    }
	    int i = 0;
	    for (i = index * ITEM_PAGE; i < lstDataEventOfNode.size() && i < (index + 1) * ITEM_PAGE; ++i) {
		insertTextFormat(lstDataEventOfNode.get(i));
	    }
	    scrollToEnd();
	}
    }//GEN-LAST:event_cb_pageActionPerformed
    private void scrollToEnd(){
	jScrollPane1.scrollRectToVisible(new Rectangle(0, 0, 1, 1));
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
	/* Set the Nimbus look and feel */
	//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
	 * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
	 */
	try {
	    for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
		if ("Nimbus".equals(info.getName())) {
		    javax.swing.UIManager.setLookAndFeel(info.getClassName());
		    break;
		}
	    }
	} catch (ClassNotFoundException ex) {
	    java.util.logging.Logger.getLogger(InfoNodeFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
	} catch (InstantiationException ex) {
	    java.util.logging.Logger.getLogger(InfoNodeFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
	} catch (IllegalAccessException ex) {
	    java.util.logging.Logger.getLogger(InfoNodeFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
	} catch (javax.swing.UnsupportedLookAndFeelException ex) {
	    java.util.logging.Logger.getLogger(InfoNodeFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
	}
	//</editor-fold>

	/* Create and display the form */
	java.awt.EventQueue.invokeLater(new Runnable() {
	    public void run() {
		//new InfoNodeFrame().setVisible(true);
	    }
	});
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_ok;
    private javax.swing.JComboBox cb_page;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JList jl_nodes;
    private javax.swing.JTextPane jtp_event;
    private javax.swing.JLabel lbl_color;
    private javax.swing.JLabel lbl_energy;
    private javax.swing.JLabel lbl_height;
    private javax.swing.JLabel lbl_id;
    private javax.swing.JLabel lbl_location;
    private javax.swing.JLabel lbl_range;
    private javax.swing.JLabel lbl_sum_event;
    private javax.swing.JLabel lbl_width;
    // End of variables declaration//GEN-END:variables
}
